package org.jrpc.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.jrpc.common.baen.RpcRequest;
import org.jrpc.common.baen.RpcResponse;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2017/8/28.
 */
@Deprecated
public class ClientHandler extends ChannelInboundHandlerAdapter {
    private ConcurrentHashMap<String,RpcResponse> map=null;
    public ClientHandler(ConcurrentHashMap<String,RpcResponse> map){
        this.map=map;
    }
    private ChannelHandlerContext ctx;
    /**
     * tcp链路简历成功后调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("成功连接服务器");
        this.ctx = ctx;

    }
    /**
     * 发送消息
     * @param msg
     * @return
     * @throws IOException
     */
    public RpcResponse sendMsg(RpcRequest msg) throws IOException {
        System.out.println("client:" + msg);
        RpcResponse response=new RpcResponse();
        map.put(msg.getRequestId(),response);
        ctx.channel().writeAndFlush(msg);
        return response;
    }
    /**
     * 收到消息后调用
     * @throws IOException
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException, CloneNotSupportedException {
        System.out.println(msg);
        if(msg instanceof RpcResponse){
            RpcResponse response= (RpcResponse) msg;
            RpcResponse re= map.get(response.getRequestId());
            re.setException(response.getException());
            re.setResult(response.getResult());
//            re.getSynchronousQueue().offer(1);
        }
//        ctx.close();
//        System.exit(0);
    }
    /**
     * 发生异常时调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //需要回调，重试接服务器 （没有实现）
        System.err.println("与服务器断开连接:"+cause.getMessage());
        ctx.close();
        System.exit(0);
    }
}
